package cloud.tianai.ram.policy.common.handler;

import cloud.tianai.ram.policy.common.handler.ConditionHandler;
import cloud.tianai.ram.policy.common.model.dto.Condition;
import cloud.tianai.ram.policy.common.model.dto.TypeDefinition;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author: 天爱有情
 * @date 2022/4/20 15:25
 * @Description 抽象的条件处理器
 */
public abstract class AbstractConditionHandler implements ConditionHandler {

    @Getter
    @Setter
    private List<TypeDefinition> typeDefinitions;

    @Override
    public boolean support(Condition condition) {
        return support(condition.getOperationType());
    }

    @Override
    public boolean support(String type) {
        for (TypeDefinition typeDefinition : typeDefinitions) {
            if (typeDefinition.equals(type)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public List<TypeDefinition> listSupportTypes() {
        return typeDefinitions == null ? Collections.emptyList() : typeDefinitions;
    }


    public void addTypeDefinition(TypeDefinition definition) {
        if (typeDefinitions == null) {
            typeDefinitions = new ArrayList<TypeDefinition>();
        }
        typeDefinitions.add(definition);
    }

    public boolean removeTypeDefinition(String type) {
        return typeDefinitions.removeIf(c -> c.equals(type));
    }
}
